/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.querie.Algos;
import com.querie.SI.PutItemData;
import com.querie.SI.PutSessionData;
import com.querie.beans.ItemS;
import com.querie.beans.SessionAll;
import com.querie.Voldemort.VoldemortH;
import com.google.gson.Gson;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.*;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



/**
 *
 * @author Naushin
 */
public class SeparateSimilarity{
   VoldemortH vold = new VoldemortH();
   //  public static  List<Integer> ls=new ArrayList<Integer>(); //Initialize list for itemNames

 public void SessionSimilarity(int session){
 //  System.out.println("Im in Session SImilarity");
         try{
        String sessionString=Integer.toString(session);
        String sessioneach= vold.getValue(sessionString, "SessionThree");


      SessionAll sessionObj=new SessionAll();
      Gson gson = new Gson();
    sessionObj = gson.fromJson(sessioneach,SessionAll.class);

   List<Integer> ls=new ArrayList<Integer>(); //Initialize list for itemNames
System.out.println("Im in Session SImilarity");
    for(int k=0; k<sessionObj.getItems().size();k++){
        String itemName=Integer.toString(sessionObj.getItems().get(k).getItemId());//each itemName
        String count=Integer.toString(sessionObj.getItems().get(k).getCount());//each corr. count
       // System.out.println("itemId: "+itemName+ "count: "+count);
         ls.add(Integer.parseInt(itemName));
           }//adding each itemName to a list
         compareSimilarity(ls,session);

        //}
          }
         catch(Exception e){
         System.out.println("Ex is "+e);
         }
        }
    public void compareSimilarity(List<Integer> ls, int session){
       Collections.sort(ls);//sorting all items

int size=ls.size();
//System.out.println("Im in compare SImilarity");
for(int i=0;i<size;i++){
                      if(ls.get(i)!=0){
                          try{
                       String lsi=Integer.toString(ls.get(i));
                       String itemLeft= vold.getValue(lsi, "ItemThree");
                       if (itemLeft==null){
                         NewElement(ls.get(i),session);
                          itemLeft= vold.getValue(lsi, "ItemThree");

                       }
               //        System.out.println(0);
                       ItemS item=new ItemS();
                       Gson gson=new Gson();
                       item=gson.fromJson(itemLeft, ItemS.class);
                       Map<String,String> hm1=new HashMap<String, String>();
                       List<String> ses=new ArrayList<String>();//sessionNames List for each item
                       List<Integer> count=new ArrayList<Integer>();//List for corr. session counts
                        List<Integer> intses=new ArrayList<Integer>();

                       for(int k=0; k<item.getSession().size();k++)
                       { //for one item
                       ses.add(Integer.toString(item.getSession().get(k).getSessionName())); //adding sessionsNames
                       intses.add(item.getSession().get(k).getSessionName());
                       count.add((item.getSession().get(k).getSessionCount()));//adding their counts
                       hm1.put(Integer.toString(item.getSession().get(k).getSessionName()),Integer.toString(item.getSession().get(k).getSessionCount()));
                       }



                     int x=ls.get(i);
                    int j=i+1;
                     while(j<size){

                       iterate(ses,x,j,ls,count,hm1,session);

                       j++;
                     }
                          }
                          catch(Exception e){System.out.println("exception is" +e);}


   }

        }
    }

   public void iterate(List<String> ses,  int i,int j, List<Integer> ls,List<Integer> count,Map<String, String> hm, int session) {
 if(ls.get(j)!=0){

                       int num=0;
                        int den=0;
                        List<Integer> numerator=null;
                        List<Integer> denominatorA=null;
                        List<Integer> denominatorB=null;


            //Check if the smilarity for the pair is present in similarity table
               String alias=i+"&"+ls.get(j).toString();


              VoldemortH v=new VoldemortH();
              try{
                  String present= v.getValue(alias, "Jaccard_3");

                  //System.out.println("Jaccard is"+present);
                 if (present!=null) {
                    return;
                    //for training return
                   //for testing continue;
                 }
else
// else

                  {


                        String x1=ls.get(j).toString();
                      String itemRight= vold.getValue(x1, "ItemThree");
                      if(itemRight==null){
                             NewElement(ls.get(j),session);
                          //  String el1=Integer.toString(el


                      }
                    //  if(itemRight!=null)
 else
                      {
                           itemRight= vold.getValue(x1, "ItemThree");

                      ItemS itemR=new ItemS();
                      Gson gson1=new Gson();
                      itemR=gson1.fromJson(itemRight, ItemS.class);
                       List<String> itm1=new ArrayList<String>();
                       Map<String,String> hm1=new HashMap<String, String>();
                      for(int k1=0; k1<itemR.getSession().size();k1++){
                      itm1.add(Integer.toString(itemR.getSession().get(k1).getSessionName()));
                      hm1.put(Integer.toString(itemR.getSession().get(k1).getSessionName()),Integer.toString(itemR.getSession().get(k1).getSessionCount()));
                        }
                        List<String> totalSessions = new ArrayList<String>();
                         List<String> totalNumSessions = new ArrayList<String>();
                        List<String> totalDenSessions = new ArrayList<String>();


                        totalSessions.addAll(ses);
                        totalSessions.addAll(itm1);//total sessions of I1 and I2
                        //HashMap<String, String> hm = new HashMap<String, String>();
                        numerator=new ArrayList<Integer>();
                        denominatorA=new ArrayList<Integer>();
                        denominatorB=new ArrayList<Integer>();
                         for(int l=0;l<totalSessions.size();l++){
                             String x= totalSessions.get(l);

                        if(totalDenSessions.contains(x)){

                            totalDenSessions.remove(x);
                              totalNumSessions.add(x) ;
                              num++;
                              den--;
                                int value1=Integer.parseInt(hm1.get(x));


                                 int value2=Integer.parseInt(hm.get(x));
                               //   System.out.println("Hm.get(x) is" +value2);

                                 int value=(value1 * value2);
                                 int sqValue1=value1 * value1;
                                 int sqValue2=value2 * value2;


                                numerator.add(value);

                                 denominatorA.add(sqValue1);
                                 denominatorB.add(sqValue2);


                        }

                            else
                        {
                            totalDenSessions.add(x);
                            den++;

                            }
                       }

    }//else for new item
                     }//else
     }catch(Exception e){System.out.print("ex is "+e);}


                           double JSimilarity= (float)num/(float)(num+(2*den));
              //      System.out.println("Jaccard similarity between: I1:"+i+"I2:"+ls.get(j)+"is: "+JSimilarity );

                    double NCSimilarity=0;
                    double DCSimilarityA=0,DCSimilarityB=0,DCSimilarity=0;
                    double CosineSimilarity=0;
                    for(int i2=0;i2<numerator.size();i2++){
                    NCSimilarity=NCSimilarity+numerator.get(i2);}
                    for(int i3=0;i3<denominatorA.size();i3++){
                    DCSimilarityA=DCSimilarityA+denominatorA.get(i3);
                    }
                    for(int i4=0;i4<denominatorB.size();i4++){
                    DCSimilarityB=DCSimilarityB+denominatorB.get(i4);
                    }
                    double x6=(DCSimilarityA*DCSimilarityB);
                    DCSimilarity=Math.sqrt(x6);
                    CosineSimilarity=(NCSimilarity/DCSimilarity);
                     //inserting similarity values into sql
                      ItemSimilarity is=new ItemSimilarity();
                  is.putValue(i,ls.get(j),JSimilarity);

                    PutSimilarity(JSimilarity,CosineSimilarity,alias);
      }

    }
public void PutSimilarity(double J, double C,String key){
  VoldemortH v=new VoldemortH();
  String Jvalue= Double.toString(J);
  v.putValue(key, Jvalue,"Jaccard_3");
  //System.out.println("Items are:"+key+"Jaccard"+Jvalue);
  String Cvalue=Double.toString(C);
  //System.out.println("Cosine"+Cvalue);
  v.putValue(key, Cvalue, "Cosine_3");


}

   public void NewElement( int j, int session)
    {
                        System.out.println("new item is "+j);
                        List<Integer> sessnList=new ArrayList<Integer>();
                       List<Integer> CntList=new ArrayList<Integer>();
                      //add into sessions
                    //  PutSessionData psd=new PutSessionData();
                     // psd.putData(session, Integer.toString(j));
                      //add item
                      PutItemData pd=new PutItemData();
                        CntList.add(1);
                       sessnList.add(session);

                      pd.putAll(j,sessnList,CntList);
                       return;

    }

public void PullSimilarity(){
VoldemortH vh= new VoldemortH();
String sesA=vh.getValue("7909&8470","Jaccard_22222");
if(sesA==null){
System.out.println("Session not present");

     }
 else System.out.println("Element found"+sesA);
 }

   public static void main(String[] args){


      SeparateSimilarity sm= new SeparateSimilarity();
     Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "querie";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "root";
    String strSQL1 = "";



        ResultSet rs0 = null;
       Statement stmt = null;


  try{
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");

           stmt = conn.createStatement();
           strSQL1= "SELECT distinct sessionId FROM sessionqueries where sessionId NOT IN (63,95,234,435,908,1011,1128,1459,2476,6731,7073,7223,7265,7444,7768,8034,8301,8370,10496,19300,19626,19760,19895,21284,21341,21380,21460,21949,22006,22023,22068,22358,24935,24989,25087,25594,25640,25886,25964,26122,26367,26742,26922,27010,27209,29899,30083,30227,30292,30477,45247,53074,53090,53186,53247,53355,53432,53484,53632,53754,53766,53942,54189,60706,60885,61013,61079,61175,61385,61433,61443) group by sessionId";
           rs0 = stmt.executeQuery(strSQL1);

           while(rs0.next()){
                System.out.println(""+rs0.getInt(1));
                if(rs0.getInt(1)>53753)
                        sm.SessionSimilarity(rs0.getInt(1));
               //    trainCount++;

           }
            conn.close();
       }
    catch(Exception ex){ex.printStackTrace();}
   }






}
